import React, { Component } from 'react';
import { Radio, InputNumber, Modal, Form, Space, Button, Input, Select, message } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheSwitch from "@/components/TheSwitch";

import ThePagination from "@/components/ThePagination";

import {
  apiGetThirdTabPage,
  apiGetThirdTabAdd,
  apiGetThirdTabEdit,
  apiGetThirdTabDetail,
  apiGetThirdTabDel,
  apiGetThirdTabUpdateStatus
} from '@/request/tripartiteMall/tab'
import {
  thirdChannelPage
} from '@/request/tripartiteMall/resourceManagement.jsx'

import store from "@/store/store"
import _ from 'lodash';

const { Option } = Select
const { confirm } = Modal;
export default class Tab extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef()
    this.state = {
      dataSource: [], //表格数据
      columns: [
        {
          title: "tab名称",
          dataIndex: "tabName",
          key: "tabName",
        },
        {
          title: "排序",
          dataIndex: "sort",
          key: "sort",
          sorter: true,
          sortDirections: ['ascend'],
          render: (text, record) => {
            return <Space>
              <InputNumber style={{minWidth:100}} min={1} max={9999} precision={0} value={record.sort} onChange={this.valueInput} />
              <Button
                type="primary"
                onClick={() => this.onSortChange(record.tabId)}
              >
                确定
              </Button>
            </Space>
          }
        },
        {
          title: "商品获取方式",
          dataIndex: "relationType",
          key: "relationType",
          render: (text, record) => {
            switch (text) {
              case 1:
                return "关键词搜索商品"
              case 2:
                return "频道商品配置"
              default:
                return "-"
            }
          }
        },
        {
          title: "关键词",
          dataIndex: "keyword",
          key: "keyword",
          render: (text, record) => {
            return text ?? "-"
          }
        },
        {
          title: "频道",
          dataIndex: "channelName",
          key: "channelName",
          render: (text, record) => {
            return text ?? "-"
          }
        },
        {
          title: "修改时间",
          dataIndex: "updateTime",
          key: "updateTime",
          render: (text, record) => {
            return text
          }
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          fixed: 'right',
          render: (text, record) => {
            return <TheSwitch checked={!!record.status}
              onChange={(v) => this.onStatusChange(v, record.tabId)} />
          }
        },
        {
          title: "操作",
          dataIndex: "goodsName",
          key: "goodsName",
          fixed: 'right',
          render: (text, record) => {
            return <Space>
              <TheButton haspermi={['tripartiteMall:tab:edit']} onClick={() => this.edit(record.tabId)}>编辑</TheButton>
              <TheButton haspermi={['tripartiteMall:tab:del']} onClick={() => this.del(record.tabId, record.status)}>删除</TheButton>
            </Space>
          }
        },
      ],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 1,
      queryForm: {},
      title: '', //弹框标题
      isModalVisible: false, // 弹框是否显示
      tabId: '', //编辑id
      sortCurrent: null, // 当前修改的排序值
      changeFlag: false, // 排序修改状态
      channelVisible: false, //频道表格弹窗
      channelColumns: [
        {
          title: "频道ID",
          dataIndex: "channelId",
          key: "channelId",
        },
        {
          title: "频道名称",
          dataIndex: "channelName",
          key: "channelName",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "商品数量",
          dataIndex: "goodsCount",
          key: "goodsCount",
        },
      ],
      channelDataSource: [],
      channelPageData: {
        pageNo: 1,
        pageSize: 10
      },
      channelTotal: 1,
      channelId: [],
      channelName: null
    }
  }

  componentDidMount() {
    this.getData()
  }

  // table列表
  getData = async (values) => {
    // if (values && 'status' in values) {
    //     if (values.status === '-1') {
    //         delete values.status
    //     }
    // }

    const params = {
      ...this.state.pageData,
      ...this.state.queryForm
    }
    let res = await apiGetThirdTabPage({ ...params })
    if (res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    }
  }

  // 排序输入框
  valueInput = (e) => {
    this.setState({ sortCurrent: e, changeFlag: true })
  }
  // 排序输入框确认按钮
  onSortChange = async (tabId) => {
    let { sortCurrent } = this.state
    // 排序数据修改
    const res = await apiGetThirdTabEdit({
      tabId,
      sort: sortCurrent,
      editFlag: false
    })
    if (res.code === 0) {
      message.success("排序修改成功")
      this.getData()
    }
  }
  // 启用/停用
  onStatusChange = async (flag, tabId) => {
    const status = flag ? 1 : 0
    const res = await apiGetThirdTabUpdateStatus({ tabId: tabId, status })
    if (res.code === 0) {
      this.getData()
    }

  }

  // 新建
  add() {
    this.setState({
      isModalVisible: true,
      title: '新建tab',
      tabId: null
    })
  }

  // 编辑
  edit(tabId) {
    this.setState({
      isModalVisible: true,
      title: '编辑tab',
      tabId: tabId,
    }, () => {
      this.tabView(tabId)
    })
  }
  tabView = (tabId) => {
    apiGetThirdTabDetail({ tabId }).then(res => {
      if (res.code === 0) {
        this.FormRef.current.setFieldsValue({ ...res.data })
        this.setState({
          channelId: [res.data.channelId],
        })
      }
    })
  }
  del = (tabId, status) => {
    if (status) {
      message.warn("开启中的tab不可删除，请关闭后再操作。")
    } else {
      confirm({
        title: '确定删除该tab吗？',
        content: '',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          apiGetThirdTabDel({ tabId: tabId }).then(res => {
            if (res.code === 0) {
              message.success("删除成功")
              this.delToPageStatus()
            }
          })
        },
        onCancel() {
        },
      });
    }
  }
  delToPageStatus = ()=>{
    let { pageData,total } = this.state
    if ((total%pageData.pageSize) === 1){
      this.pageChange(pageData.pageNo-1,pageData.pageSize)
    }
    else {
      this.pageChange(pageData.pageNo,pageData.pageSize)
    }
  }
  // 取消
  handleCancel = () => {
    this.FormRef.current.resetFields()
    this.setState({
      isModalVisible: false,
    })
  };
  // 确定新增/修改
  handleFinish = async (values) => {
    values.channelId = this.state.channelId.toString()
    if (this.state.tabId) {
      let res = await apiGetThirdTabEdit({
        ...values,
        tabId: this.state.tabId,
        editFlag: true
      })
      if (res.code === 0) {
        React.$message({
          type: 'success',
          content: '修改成功'
        })
        this.handleCancel()
        this.getData()
      }
    } else {
      let res = await apiGetThirdTabAdd({ ...values })
      if (res.code === 0) {
        React.$message({
          type: 'success',
          content: '新建成功'
        })
        this.handleCancel()
        this.getData()
      }
    }

  };
  // 分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize,
      },
    }, () => {
      this.getData()
    })
  };

  // 表格升序降序
  handleTableChange = (pagination, filters, sorter) => {
    let { queryForm } = this.state
    queryForm.orderByAsc = sorter.order === 'ascend' ? 'sort' : null
    // queryForm.orderByDesc = sorter.order === 'descend' ? 'sort' : null
    this.setState({ queryForm }, () => {
      this.getData()
    })
  }
  // 频道弹窗
  openChannel = () => {
    this.setState({
      channelVisible: true
    }, () => {
      this.getChannelData()
    })
  }
  getChannelData() {
    thirdChannelPage({ ...this.state.channelPageData }).then(res => {
      if (res.code === 0) {
        this.setState({
          channelDataSource: res.data,
          channelPageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          channelTotal: res.totalCount
        })
      }
    })
  }
  // 频道弹窗保存
  handleChannelOk = () => {
    this.FormRef.current.setFieldsValue({
      channelName: this.state.channelName
    });
    this.setState({
      channelVisible: false
    })
  }
  // 频道弹窗取消
  handleChannelCancel = () => {
    this.setState({
      channelVisible: false,
      channelID: []
    })
  }
  // 弹窗分页
  channelPageChange = (pageNo, pageSize) => {
    this.setState({
      channelPageData: {
        pageNo,
        pageSize,
      },
    }, () => {
      this.getChannelData()
    })
  };
  // 表格选择
  onSelectChange = (selected, selectedRows) => {
    this.setState({
      channelId: selected,
      channelName: selectedRows[0].channelName
    })
  }
  render() {
    let {
      dataSource,
      columns,
      total,
      pageData,
      channelColumns,
      channelDataSource,
      channelTotal,
      channelPageData,
      isModalVisible,
      title,
      channelVisible,
      channelId
    } = this.state
    const rowSelection = {
      selectedRowKeys: channelId,
      // preserveSelectedRowKeys: true,
      onChange: this.onSelectChange,
      type: 'radio'
    }
    return (
      <div className="p-layout-box commodity-content">
        <div style={{ width: "120px", marginBottom: "10px" }}>
          <TheButton haspermi={['tripartiteMall:tab:add']} type={'primary'} size={'middle'} onClick={() => {
            this.add()
          }}>新建</TheButton>
        </div>
        <TheTable
          scroll={{ x: "max-content", y: "63vh" }}
          columns={columns}
          dataSource={dataSource}
          onChange={this.handleTableChange}
        />
        <ThePagination
          pageNo={pageData.pageNo}
          pageSize={pageData.pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        <Modal
          title={title}
          visible={isModalVisible}
          maskClosable={false}
          width="30%"
          onCancel={() => this.handleCancel()}
          footer={null}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.handleFinish(values)}
          >
            <Form.Item
              label="tab名称"
              name="tabName"
              rules={[
                {
                  required: true,
                  message: '请输入tab名称!',
                },
              ]}
              extra={"将在APP展示，请注意规范命名"}
            >
              <Input maxLength={6} placeholder='最多允许输入6个字' />
            </Form.Item>

            <Form.Item
              label="商品获取方式"
              name="relationType"
              initialValue={1}
              rules={[{ required: true, message: "请选择商品获取方式" }]}
            >
              <Radio.Group>
                <Radio value={1}>关键词搜索商品</Radio>
                <Radio value={2}>频道商品配置</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.relationType !== currentValues.relationType}
            >
              {({ getFieldValue }) =>
                getFieldValue('relationType') === 1 ? (
                  <Form.Item
                    name="keyword"
                    label="搜索关键词"
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                  >
                    <Input placeholder='请输入搜索关键词' />
                  </Form.Item>
                ) : null
              }
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.relationType !== currentValues.relationType}
            >
              {({ getFieldValue }) =>
                getFieldValue('relationType') === 2 ? (
                  <Form.Item
                    name="channelName"
                    label="频道商品配置"
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                  >
                    <Input readOnly={true} placeholder='点击选择频道' onClick={this.openChannel} />
                  </Form.Item>
                ) : null
              }
            </Form.Item>
            <Form.Item
              label="排序"
              name="sort"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber min={1} max={9999} precision={0} placeholder='排序越小越靠前' />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>

                <Button type="default" onClick={() => this.handleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title={"选择频道"}
          visible={channelVisible}
          width="70%"
          onOk={() => this.handleChannelOk()}
          onCancel={() => this.handleChannelCancel()}
          okText={'保存'}
          maskClosable={false}
          okButtonProps={{ disabled: !channelId.length }}
        >
          <TheTable
            scroll={{ x: "max-content", y: "63vh" }}
            columns={channelColumns}
            dataSource={channelDataSource}
            rowSelection={rowSelection}
            rowKey={'channelId'}
          />
          <ThePagination
            pageNo={channelPageData.pageNo}
            pageSize={channelPageData.pageSize}
            total={channelTotal}
            pageChange={this.channelPageChange}
          />
        </Modal>
      </div>
    );
  }
}
